package com.example.demo.read_write;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ClassName: ReadWriteLockDemo
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/08/01-00:08:00
 * Description:
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();

    /**
     * 写操作
     */
    public void put(String key, Object value) throws InterruptedException {
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "线程,正在写入key:" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "线程,完成写入key:" + key);
        } finally {
            rwLock.writeLock().unlock();
        }

    }

    /**
     * 读操作
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        Object object = null;
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "线程,正在读取key:" + key);
            object = map.get(key);
            System.out.println(Thread.currentThread().getName() + "线程,完成读取value:" + object);
        } finally {
            rwLock.readLock().unlock();
        }

        return object;
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        /**
         * 五个线程写，五个线程读
         */
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                try {
                    myCache.put(String.valueOf(num), num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }

        /**
         * 五个线程读
         */
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.get(String.valueOf(num));
            }, String.valueOf(i)).start();
        }


    }
}
